from qiskit import QuantumCircuit, transpile
from qiskit_aer import Aer
from qiskit.visualization import plot_histogram, circuit_drawer
import matplotlib.pyplot as plt  # 新增导入

# 1. 构建贝尔态电路
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()  # 测量所有量子比特

# 绘制量子电路图
circuit_drawer(qc, output='mpl')
plt.show()

# 2. 执行模拟
backend = Aer.get_backend('qasm_simulator')

# 编译电路以适应后端
qc = transpile(qc, backend)

# 执行模拟前获取初始状态
initial_counts = {'00': 0, '11': 0}
plot_histogram(initial_counts, title="Initial State (Before Execution)", bar_labels=False)
plt.ylim(0, 800)
plt.show()

# 执行模拟过程中的随机值
job = backend.run(qc, shots=300)  # 运行300次以获取过程中的随机值
intermediate_counts = job.result().get_counts(qc)
plot_histogram(intermediate_counts, title="Intermediate State (During Execution)", bar_labels=False)
plt.ylim(0, 800)
plt.show()

# 执行模拟
job = backend.run(qc, shots=1024)  # shots: 模拟次数

# 获取结果
counts = job.result().get_counts(qc)  # 必须传入qc

# 3. 可视化与显示
plot_histogram(counts, title="Measurement Results (After Execution)", bar_labels=False)
plt.ylim(0, 800)
plt.show()  # 新增显示命令
